package ClientCommands;

import Commands.ClientCommandBase;
import DomainLayer.CommentaryEntity;
import Helpers.ApplicationLogger;
import ServiceLayer.ServiceFacade;
import org.json.simple.JSONObject;

import java.io.IOException;

public class EditCommentary extends ClientCommandBase<Boolean> {
    private int commentaryId;
    private int userId;
    private String text;

    private void setCommentaryId(int id) {
        commentaryId = id;
    }

    private void setCommentaryId(String str) {
        try {
            commentaryId = Integer.parseInt(str);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void setText(String str) {
        text = str;
    }
    private void setUserId(int id) {
        userId = id;
    }

    private void setUserId(String str) {
        try {
            userId = Integer.parseInt(str);
        }
        catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public void FillFromJSON(JSONObject jObj) {
		super.FillFromJSON(jObj);
		setCommentaryId((String)jObj.get("commentaryId"));
        setUserId((String)jObj.get("userId"));
        setText((String)jObj.get("text"));
    }

    protected void ExecuteInternal() throws IOException {
        try {
            CommentaryEntity commentary = ServiceFacade.getInstance().GetCommentaryById(commentaryId);
            Boolean result = false;
            if (commentary != null) {
                commentary.setText(text);
                ServiceFacade.getInstance().UpdateCommentary(commentary);
                result = true;
            }
            setResult(result);
        } catch (Throwable e) {
            ApplicationLogger.getInstance().LOG.error(e.getMessage());
        }
    }
}
